package com.yindian.cos.easy.security.authentication.login.social.weixin;

import com.yindian.cos.easy.security.authentication.login.social.core.AbstractSocialAuthentication;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.WeiXinProperties;
import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 微信登录拦截器
 *
 * @author zhangchuanhao
 * @create 2018/11/19 13:10
 */
@Log4j2
public class WeiXinLoginAuthentication extends AbstractSocialAuthentication {

    private final WeiXinProperties weiXinProperties;

    private final String loginUrl;

    private final String method;

    public WeiXinLoginAuthentication(EasySecurityProperties easySecurityProperties) {
        this.weiXinProperties = easySecurityProperties.getWeixin();
        this.loginUrl = weiXinProperties.getLoginUrl();
        this.method = weiXinProperties.getMethod();
    }

    @Override
    public boolean support(HttpServletRequest request) {
        return support(request, method, loginUrl);
    }

    @Override
    public int order() {
        return weiXinProperties.getOrder();
    }

    @Override
    public void redirectAuthorization(HttpServletResponse response) throws IOException {
        String url = weiXinProperties.getAuthorizationCodeUrl();
        url += "?appid=" + weiXinProperties.getAppId();
        url += "&redirect_uri=" + URLEncoder.encode(weiXinProperties.getDomain() + weiXinProperties.getRedirectUri(), "utf-8");
        url += "&response_type=" + weiXinProperties.getResponseType();
        url += "&state=" + weiXinProperties.getState();
        url += "&scope=" + weiXinProperties.getScope();
        response.sendRedirect(url);
        log.debug(ProviderName.WEIXIN + "登录引导用户跳转至授权页面...");
    }
}
